// 数据表格
const list = document.querySelector('.list')
// 获取UID
const UID = localStorage.getItem('UID')
// 插入数据
const insert = document.querySelector('.insert')
const insertShow = document.querySelector('.insertShow')
const inputs = document.querySelectorAll('.insertShow input')
const select = document.querySelector('.insertShow select')
const peopleSumSelect = document.querySelector('#peopleSum')
const locations = document.querySelector('.insertShow .location')
const cancel = document.querySelector('.cancel')
const add = document.querySelector('.add')
// 表格控制栏
const first = document.querySelector('.first')
const last = document.querySelector('.last')
const next = document.querySelector('.next')
const theLast = document.querySelector('.theLast')
const paged = document.querySelector('.paged')
const pageSum = document.querySelector('.controlTable select')
const allPage = document.querySelector('.allPage')

// 添加/更新状态
let statusInsert = 0

// 记录要更新的课程
let oldCourseId

// 页码
let page = 1
let pageNumber = 5
// 记录最大页数
let maxPage = 0

// 记录职称
let jobTitle = 1


async function getPageSum() {
  const result = (await axios({
    url: 'http://127.0.0.1:8080/Teacher/CourseManagement/getCoursePage',
    params: {
      id: UID,
      pageSum: pageNumber
    }
  })).data.data
  maxPage = allPage.innerHTML = result
}

getPageSum()

async function getAllCourse() {
  const result = (await axios({
    url: 'http://127.0.0.1:8080/Teacher/CourseManagement/getAllCourse',
    params: {
      UID,
      page,
      pageSum: pageNumber
    }
  })).data.data
  // 获取教师名字
  const name = (await axios({
    url: 'http://127.0.0.1:8080/Teacher/CourseManagement/getTeacherNameById',
    params: {
      UID
    }
  })).data.data
  const htmlStr = result.map((e, key) => {
    const degreeValueArr = e.degreeDemand
    let degreeArr = ''
    for (let i = 0; i < degreeValueArr.length; i++) {
      const degree = degreeValueArr[i]
      if (degree.indexOf("1") !== -1) {
        degreeArr += ' 专科'
      } else if (degree.indexOf("2") !== -1) {
        degreeArr += ' 本科'
      } else if (degree.indexOf("3") !== -1) {
        degreeArr += ' 硕士研究生'
      } else if (degree.indexOf("4") !== -1) {
        degreeArr += ' 博士研究生'
      } else if (degree.indexOf("5") !== -1) {
        degreeArr += ' 博士后研究生'
      }
    }
    return `
      <tr data-id=${key}>
        <td>${e.id}</td>
        <td>${e.name}</td>
        <td>${e.credit}</td>
        <td>${name}</td>
        <td>${e.day}</td>
        <td>${e.time}</td>
        <td>${e.location}</td>
        <td>${e.constantTime}</td>
        <td>${e.instructionalMethod}</td>
        <td class="degreeBox">${degreeArr}</td>
        <td>${e.peopleNumber}/${e.peopleSum}</td>
        <td>
          <button class="update" data-id="${key}">修改</button>
          <button class="delete" data-id="${key}">删除</button>
        </td>
      </tr>
    `
  }).join('')
  list.innerHTML = htmlStr
}

getAllCourse()      // 获取全部课程


insert.addEventListener('click', async () => {
  jobTitle = (await axios({
    url: 'http://127.0.0.1:8080/Teacher/PersonData/Information',
    params: {
      id: localStorage.getItem('UID')
    }
  })).data.data
  if (jobTitle == '1') {
    alert('助教暂未开放课程管理功能')
    return
  }
  statusInsert = 0
  add.innerHTML = '增加'
  insertShow.style.display = 'block'
})

cancel.addEventListener('click', () => {
  for (let i = 0; i < inputs.length; i++) {
    inputs[i].value = ''
    if (inputs[i].type === 'checkbox') {
      inputs[i].checked = false
    }
  }
  insertShow.style.display = 'none'
})

// 新增课程
add.addEventListener('click', async () => {
  if (statusInsert === 1) {
    return
  }
  const name = inputs[0].value
  if (!/^[^\s]{1,30}$/.test(name)) {
    alert('名字不符合规范')
    return
  }
  const credit = +inputs[1].value
  if (credit < 0.1 || credit > 4) {
    alert('学分不合要求')
    return
  }
  const day = +inputs[2].value
  if (day < 1 || day > 7) {
    alert('上课天数范围为1~7')
    return
  }
  const time = +inputs[3].value
  if (time < 1 || time > 14) {
    alert('上课节数范围为1~14')
    return
  }
  const constantTime = +inputs[4].value
  if (constantTime < 1 || constantTime > 14 || time + constantTime - 1 > 14) {
    alert('课程时长不符合要求')
    return
  }
  const location = inputs[5].value
  if (window.getComputedStyle(locations).getPropertyValue('display') != 'none' && !/^[^\s]{1,30}$/.test(location)) {
    alert('地址名字不符合规范')
    return
  }
  // 可选课学历人群
  let degreeValueArr = ''
  const degreeArr = document.querySelectorAll('.degreeSelect input[name="degree"]:checked')
  if (degreeArr.length == 0) {
    alert('至少选择一种学历')
    return
  }
  for (let i = 0; i < degreeArr.length; i++) {
    degreeValueArr += degreeArr[i].value
  }
  // 获取选课上限人数
  const peopleCourseSum = peopleSumSelect.value
  if (jobTitle < 3 && peopleCourseSum > 60) {
    alert('讲师选课人数上限为60人')
    return
  } else if (jobTitle < 4 && peopleCourseSum > 120) {
    alert('高级选课人数上限为120人')
    return
  }
  const isTheSameTime = (await axios({
    url: 'http://127.0.0.1:8080/Teacher/CourseManagement/isTheSameTimeCourse',
    params: {
      UID,
      day,
      startTime: time,
      constTime: constantTime
    }
  })).data.data
  if (!isTheSameTime) {
    alert('添加课程与已存在课程的时间存在冲突')
    return
  }
  // 获取课程号
  const courseId = (await axios({
    url: 'http://127.0.0.1:8080/Teacher/CourseManagement/getCourseId'
  })).data.data
  axios({
    url: 'http://127.0.0.1:8080/Teacher/CourseManagement/addNewCourse',
    method: 'POST',
    data: {
      id: courseId,
      name,
      credit,
      teacher: UID,
      day,
      time,
      location: select.value == 1 ? '' : location,
      constantTime,
      instructionalMethod: select.value == 1 ? '线上授课' : '线下授课',
      degreeDemand: degreeValueArr,
      peopleNumber: 0,
      peopleSum: peopleCourseSum
    }
  }).then(() => {
    alert('添加成功')
    getPageSum()
    for (let i = 0; i < inputs.length; i++) {
      inputs[i].value = ''
    }
    insertShow.style.display = 'none'
    getAllCourse()
  }).catch(() => {
    alert('添加失败')
  })
})

// 更新课程
add.addEventListener('click', async () => {
  if (statusInsert === 0) {
    return
  }
  const name = inputs[0].value
  if (!/^[^\s]{1,30}$/.test(name)) {
    alert('名字不符合规范')
    return
  }
  const credit = +inputs[1].value
  if (credit < 0.1 || credit > 4) {
    alert('学分不合要求')
    return
  }
  const day = +inputs[2].value
  if (day < 1 || day > 7) {
    alert('上课天数范围为1~7')
    return
  }
  const time = +inputs[3].value
  if (time < 1 || time > 14) {
    alert('上课节数范围为1~14')
    return
  }
  const constantTime = +inputs[4].value
  if (constantTime < 1 || constantTime > 14 || time + constantTime - 1 > 14) {
    alert('课程时长不符合要求')
    return
  }
  const location = inputs[5].value
  if (window.getComputedStyle(locations).getPropertyValue('display') != 'none' && !/^[^\s]{1,30}$/.test(location)) {
    alert('地址名字不符合规范')
    return
  }
  // 可选课学历人群
  let degreeValueArr = ''
  const degreeArr = document.querySelectorAll('.degreeSelect input[name="degree"]:checked')
  if (degreeArr.length == 0) {
    alert('至少选择一种学历')
    return
  }
  for (let i = 0; i < degreeArr.length; i++) {
    degreeValueArr += degreeArr[i].value
  }
  // 获取选课上限人数
  const peopleCourseSum = peopleSumSelect.value
  if (jobTitle < 3 && peopleCourseSum > 60) {
    alert('讲师选课人数上限为60人')
    return
  } else if (jobTitle < 4 && peopleCourseSum > 120) {
    alert('高级选课人数上限为120人')
    return
  }
  const isTheSameTime = (await axios({
    url: 'http://127.0.0.1:8080/Teacher/CourseManagement/isTheSameTimeCourse',
    params: {
      UID,
      day,
      startTime: time,
      constTime: constantTime,
      classId: oldCourseId
    }
  })).data.data
  if (!isTheSameTime) {
    alert('添加课程与已存在课程的时间存在冲突')
    return
  }
  axios({
    url: 'http://127.0.0.1:8080/Teacher/CourseManagement/updateCourse?oldId=' + oldCourseId,
    method: 'POST',
    data: {
      name,
      credit,
      teacher: UID,
      day,
      time,
      location: select.value == 1 ? '' : location,
      constantTime,
      instructionalMethod: select.value == 1 ? '线上授课' : '线下授课',
      degreeDemand: degreeValueArr,
      peopleNumber: 0,
      peopleSum: peopleCourseSum
    }
  }).then(() => {
    alert('更新成功')
    for (let i = 0; i < inputs.length; i++) {
      inputs[i].value = ''
      if (inputs[i].type === 'checkbox') {
        inputs[i].checked = false
      }
    }
    insertShow.style.display = 'none'
    getAllCourse()
  }).catch(() => {
    alert('更新失败')
  })
})

select.addEventListener('change', () => {
  const classWay = select.value
  if (classWay == 2) {
    locations.style.display = 'block'
  } else {
    locations.style.display = 'none'
  }
})

// 冒泡更新数据
list.addEventListener('click', (e) => {
  statusInsert = 1
  add.innerHTML = '更新'
  const element = e.target
  if (!element.classList.contains('update')) {
    return
  }
  insertShow.style.display = 'block'
  const dataId = element.dataset.id
  const classId = oldCourseId = document.querySelector(`tr[data-id="${dataId}"] td`).innerHTML
  axios({
    url: 'http://127.0.0.1:8080/Teacher/CourseManagement/getCourseById',
    params: {
      id: classId
    }
  }).then(result => {
    const information = result.data.data
    inputs[0].value = information.name
    inputs[1].value = information.credit
    inputs[2].value = information.day
    inputs[3].value = information.time
    inputs[4].value = information.constantTime
    for (let i = 0; i < select.options.length; i++) {
      const option = select.options[i]
      if (option.text === information.instructionalMethod) {
        select.selectedIndex = i
        break
      }
    }
    if (information.instructionalMethod === '线下授课') {
      locations.style.display = 'block'
      locations.value = information.location
    } else {
      locations.style.display = 'none'
    }
  })
})

// 冒泡删除数据
list.addEventListener('click', (e) => {
  const element = e.target
  if (!element.classList.contains('delete')) {
    return
  }
  const dataId = element.dataset.id
  const deleteId = document.querySelector(`tr[data-id="${dataId}"] td`).innerHTML
  const isDelete = +confirm(`删除课程号为${deleteId}的课程`)
  if (isDelete == 0) {
    return
  }
  axios({
    url: 'http://127.0.0.1:8080/Teacher/CourseManagement/deleteCourse',
    method: 'POST',
    params: {
      id: deleteId
    }
  }).then(() => {
    getPageSum()
    getAllCourse()
  }).catch(() => {
    alert('删除失败')
  })
})



// 表格控件监听
first.addEventListener('click', () => {
  page = 1
  getAllCourse(page, pageNumber)
})

last.addEventListener('click', () => {
  if (page > 1) {
    getAllCourse(--page, pageNumber)
  }
})

next.addEventListener('click', () => {
  getPageSum()
  if (page < maxPage) {
    getAllCourse(++page, pageNumber)
  }
})

theLast.addEventListener('click', () => {
  page = maxPage
  getAllCourse(page, pageNumber)
})

pageSum.addEventListener('change', () => {
  pageNumber = pageSum.value
  page = 1
  getAllCourse(page, pageNumber)
  getPageSum()
})

paged.addEventListener('change', () => {
  page = paged.value
  // 限定page范围
  page = page > maxPage ? maxPage : page
  page = page < 1 ? 1 : page
  getAllCourse(page, pageNumber)
})